<script setup>
import { ref, onMounted, onBeforeUnmount, watch, computed, nextTick } from 'vue'
import * as echarts from 'echarts'

// ------- 可配置输入（支持外部传参） -------
const props = withDefaults(defineProps<{
  // 流量曲线：单位 L/s；数组索引默认表示时间点（可理解为秒或采样点）
  flowSeries?: number[]
  // 一秒用力呼气量（L）
  fev1?: number
  // 用力肺活量（L）
  fvc?: number
  // FEV1/FVC 判阳阈值（小数形式，默认 0.70 = 70%）
  ratioThreshold?: number
}>(), {
  flowSeries: () => [0,0,0,0.2,0.8,2.1,3.6,4.0,4.4,4.2,3.8,2.9,1.1,0.2,0,0,0],
  fev1: 4.22,
  fvc: 5.41,
  ratioThreshold: 0.70
})

// ------- 派生数据 -------
const fev1FvcRatio = computed(() => {
  if (!props.fvc) return 0
  return props.fev1 / props.fvc
})

const diagnosis = computed(() => {
  const ok = fev1FvcRatio.value >= props.ratioThreshold
  return {
    text: ok ? '正常' : '异常',
    color: ok ? '#52c41a' : '#f5222d',
    iconBg: ok ? 'rgba(82,196,26,.12)' : 'rgba(245,34,45,.12)'
  }
})

// ------- 图表 -------
const chartRef = ref<HTMLDivElement | null>(null)
let chart: echarts.ECharts | null = null
let ro: ResizeObserver | null = null

const buildOption = () => {
  const xData = props.flowSeries.map((_, i) => i) // 简单用采样点做横轴
  const maxY = Math.max(2.5, Math.max(...props.flowSeries) * 1.2)

  return {
    grid: { left: 40, right: 20, top: 36, bottom: 28 },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        if (!params?.length) return ''
        const p = params[0]
        return `t=${p.axisValue}s<br/>Flow: ${Number(p.data).toFixed(2)} L/s`
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisLine: { lineStyle: { color: '#D9D9D9' } },
      axisLabel: { color: '#888' },
      data: xData
    },
    yAxis: {
      type: 'value',
      name: 'Flow (L/s)',
      nameTextStyle: { color: '#666', padding: [0, 0, 0, -4] },
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { lineStyle: { color: '#EFEFEF' } },
      max: maxY
    },
    series: [
      {
        type: 'line',
        smooth: true,
        symbol: 'none',
        data: props.flowSeries,
        lineStyle: { width: 2 },
        areaStyle: { opacity: 0.25 }
      }
    ]
  }
}

const renderChart = () => {
  if (!chartRef.value) return
  if (!chart) chart = echarts.init(chartRef.value)
  chart.setOption(buildOption())
}

onMounted(() => {
  nextTick(renderChart)
  // 自适应
  ro = new ResizeObserver(() => chart?.resize())
  if (chartRef.value && ro) ro.observe(chartRef.value)
  window.addEventListener('resize', handleResize)
})

const handleResize = () => chart?.resize()

onBeforeUnmount(() => {
  if (ro && chartRef.value) ro.unobserve(chartRef.value)
  window.removeEventListener('resize', handleResize)
  chart?.dispose()
  chart = null
})

watch(() => props.flowSeries, () => renderChart(), { deep: true })
</script>

<template>
  <div class="lung-container">
    <h3 class="panel-title">
      <span class="dot"></span>
      4. 肺功能（FEV1/FVC）检测
    </h3>

    <!-- 图表卡片 -->
    <div class="card chart-card">
      <div class="sub-title">Flow (L/s)</div>
      <div ref="chartRef" class="chart"></div>
    </div>

    <!-- 指标卡片 -->
    <div class="card metrics-card">
      <div class="metric-row">
        <div class="metric-label">FEV1（第一秒用力呼气量）</div>
        <div class="metric-value">
          <span class="strong">{{ props.fev1.toFixed(2) }}</span>L
        </div>
      </div>

      <div class="metric-row">
        <div class="metric-label">FVC（用力肺活量）</div>
        <div class="metric-value">
          <span class="strong">{{ props.fvc.toFixed(2) }}</span>L
        </div>
      </div>

      <div class="metric-row">
        <div class="metric-label">FEV1/FVC 比值</div>
        <div class="metric-value">
          <span class="strong">{{ (fev1FvcRatio * 100).toFixed(1) }}%</span>
          <span class="threshold">≥ {{ (props.ratioThreshold * 100).toFixed(1) }}%</span>
        </div>
      </div>

      <div class="metric-row result">
        <div class="metric-label">诊断结果</div>
        <div class="metric-value">
          <span class="status" :style="{ color: diagnosis.color, background: diagnosis.iconBg }">
            {{ diagnosis.text }}
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.lung-container {
  padding: 16px 20px 20px;
  font-family: "Microsoft YaHei", system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
  color: #333;
}

.panel-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 700;
  font-size: 18px;
  margin: 0 0 12px;
}
.panel-title .dot {
  width: 6px;
  height: 16px;
  background: #1890ff;
  border-radius: 3px;
}

.card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0,0,0,0.06);
  border: 1px solid #f0f0f0;
}

.chart-card {
  padding: 8px 12px 12px;
}

.sub-title {
  font-size: 13px;
  color: #8c8c8c;
  padding: 6px 4px 0;
}

.chart {
  width: 100%;
  height: 240px;
}

.metrics-card {
  margin-top: 10px;
  padding: 8px 12px;
}

.metric-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 6px;
  border-bottom: 1px dashed #eee;
}

.metric-row:last-child {
  border-bottom: none;
}

.metric-label {
  color: #666;
  font-size: 14px;
}

.metric-value {
  font-size: 14px;
  color: #595959;
}

.metric-value .strong {
  font-weight: 700;
  font-size: 16px;
  color: #262626;
  margin-right: 4px;
}

.metric-value .threshold {
  margin-left: 8px;
  color: #8c8c8c;
  font-size: 12px;
}

.metric-row.result .status {
  padding: 2px 10px;
  border-radius: 999px;
  font-weight: 600;
  font-size: 13px;
}
</style>